import pandas as pd
import numpy as np
import sys,re
import os
#from func.che_conf import public_func_dir#A_data_check.
#print(public_func_dir)
public_func_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(public_func_dir)
# print(public_func_dir)


#from public_func_self.log import logger2

from public_func.db_control.feb_read_144 import date_col_cal
from func.df_func import replace_column_names,format_percentage_columns,columns_replace_dict
from valueCheckfunc.calculate import CatebaseData,baseData,baseData_model,baseData_url
from valueCheckfunc.dataread import df_field_add,origin_data
from func.che_conf import week_handlecate_code,month_handlecate_code#A_data_check.
from func.date_func import cycles
import argparse


columns_list = [
         ["categoryCode", "category",  'brandCode',"modelCode"],
         ["categoryCode","category",  'price_range',"modelCode"],
         ["categoryCode","category",  "field", "fieldvalue","modelCode"]
]
#columns_replace_dict={'categoryCode': '品类代码','category': '品类','count':'量','total':'额','price':'均价',"modelCode":'型号代码','model':'型号','brand':'品牌',"channelCode":'渠道代码'}


def main(year_, cycle, date_status, channelcode=None, cateCode_=None):
    status_mark = date_col_cal(date_status)
    read_mark = "" if status_mark == "week" else "M"
    output=r"D:\data\pricecheck\{}\{}{}\{}{}{}核查.xlsx".format(year_, read_mark, cycle, year_, status_mark, cycle)
    date_dicts = cycles(year_,cycle,status_mark ,rollback = 2)
    print("date_dicts",date_dicts)
    df_origin = origin_data(date_dicts, date_status=status_mark , channelcode=channelcode, cateCode=cateCode_)
    df_cate = CatebaseData(df_origin)
    
    #筛掉部分品类
    cate_filter=df_cate["categoryCode"].drop_duplicates()
    df_filter=df_origin.loc[df_origin["categoryCode"].isin(cate_filter)]
    df_model=pd.DataFrame()
    #循环生成表并输出
    with  pd.ExcelWriter(output) as writer:
        df_cate=format_percentage_columns(df_cate,df_cate.columns[2:6])
        df_cate=replace_column_names(df_cate, columns_replace_dict)
        df_cate.to_excel(writer, sheet_name= 'category', index=False)
        for i in range(len(columns_list)):
            level_col=columns_list[i][:-1]
            print("level_col",level_col)
            if "field" in level_col:
                df_filter=df_field_add(df_filter)
            df_level=baseData(df_filter,  level_=level_col, level_columns=["标记", "channelCode"])
            df_level_model=baseData_model(df_filter,level_=columns_list[i], level_columns=["标记", "channelCode"])
            #df_level筛选df_level_model
            filter_list=df_level[level_col].drop_duplicates()
            df_merge=filter_list.merge(df_level_model,how="left",on=level_col)
            df_model=pd.concat([df_model,df_merge],axis=0)
            #去重
            df_model.drop_duplicates(subset=['categoryCode', 'modelCode'], inplace=True)
            df_level=replace_column_names(df_level, columns_replace_dict)
            df_level=format_percentage_columns(df_level,df_level.columns[-8:])
            df_level.to_excel(writer, sheet_name= level_col[2], index=False)
        df_url=baseData_url(df_origin,df_model[['categoryCode', 'modelCode', 'category', 'model', 'brand']])
        df_model.drop(['brandCode', 'price_range','field','fieldvalue'],axis=1,inplace=True)
        df_model=replace_column_names(df_model, columns_replace_dict)
        df_url=replace_column_names(df_url, columns_replace_dict)
        df_model=format_percentage_columns(df_model,df_model.columns[5:9])
        df_url=format_percentage_columns(df_url,df_url.columns[7:11])
        df_model.to_excel(writer, sheet_name= "Top型号表", index=False)
        df_url.to_excel(writer, sheet_name= "综合Url表", index=False)
    return output  
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Run ModelCheck.py with arguments')
    parser.add_argument('arg1', type=int, help='First argument')
    parser.add_argument('arg2', type=str, help='Second argument')
    parser.add_argument('arg3', type=str, help='third argument')
    parser.add_argument('arg4', type=str, help='fourth argument')
    parser.add_argument('arg5', type=str, help='fifth argument')
    
    args = parser.parse_args()
    
    # 调用 main 函数，并传入解析的参数
    main(args.arg1, args.arg2, args.arg3, args.arg4, args.arg5)

#main(2025,11,"ONLINE",channelcode=["0102","0135"],cateCode_=week_handlecate_code)#week_handlecate_code
#main(2025,2,"ONLINE_M",channelcode=["0102","0135"],cateCode_=month_handlecate_code)#cateCode_=['01']month_handlecate_code
